<template>
  <div>
    <a-button @click="add" type="primary" icon="plus" style="margin-bottom: 16px;margin-right: 10px" v-show="mainId"
      >新增</a-button
    >
    <a-button @click="editAll()" type="primary" icon="edit" style="margin-bottom: 16px;margin-right: 10px"
      >编辑</a-button
    >
    <a-button @click="saveAll()" type="primary" icon="save" style="margin-bottom: 16px">保存</a-button>
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
      <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
      <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
      >项
      <a style="margin-left: 24px" @click="onClearSelected">清空</a>
    </div>

    <a-table
      ref="table"
      size="middle"
      :scroll="{ x: true }"
      bordered
      rowKey="id"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="ipagination"
      :loading="loading"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      class="j-table-force-nowrap"
      @change="handleTableChange"
    >
      <template slot="stepOrder" slot-scope="text, record">
        <a-input-number v-if="record.editable" v-model="record.stepOrder" :min="1" :max="1000"></a-input-number>
        <span v-else>{{ text }}</span>
      </template>

      <template slot="materialCode" slot-scope="text, record">
        <HfMaterialSearchSelectTag
          v-if="record.editable"
          v-model="record.materialCode"
          :material-field="['step_dictText', 'materialCode', 'materialName', 'sap']"
          :data-url="url.materialList"
          style="width:200px"
          @change="onMaterialChange(arguments, record)"
        ></HfMaterialSearchSelectTag>
        <span v-else>{{ text }}</span>
      </template>

      <template slot="action" slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="save(record)">保存</a>
            <a-divider type="vertical" style="background-color: grey"></a-divider>
            <a @click="cancel(record)">取消</a>
          </span>
          <span v-else>
            <a @click="edit(record)">编辑</a>
            <a-divider type="vertical" style="background-color: grey"></a-divider>
            <a @click="handleDelete(record.id)">删除</a>
          </span>
        </div>
      </template>
    </a-table>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, postAction, putAction } from '@api/manage'
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'

export default {
  name: 'HfRoutingDetailList',
  components: { HfMaterialSearchSelectTag },
  mixins: [JeecgListMixin],
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    }
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['sourceId'] = val
          this.loadData(1)
          this.$emit('getSteps', this.dataSource)
        }
      }
    }
  },
  data() {
    return {
      disableMixinCreated: true,
      /* 排序参数 */
      isorter: {
        column: 'stepOrder',
        order: 'asc'
      },
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '工序顺序',
          align: 'center',
          dataIndex: 'stepOrder',
          scopedSlots: { customRender: 'stepOrder' }
        },
        {
          title: '工序',
          align: 'center',
          dataIndex: 'stepId_dictText'
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: {
            customRender: 'materialCode'
          }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '默认仓库',
          align: 'center',
          dataIndex: 'warehouse_dictText'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/production/hfRouting/listHfRoutingDetailByMainId',
        materialList: '/material/hfBom/queryByMaterialCodeOrName',
        add: '/production/hfRouting/addHfRoutingDetail',
        edit: '/production/hfRouting/editHfRoutingDetail',
        editBatch: '/production/hfRouting/editHfRoutingDetailBatch',
        delete: '/production/hfRouting/deleteHfRoutingDetail'
      }
    }
  },
  methods: {
    add() {
      // 一些默认参数
      let defaultParam = {
        stepOrder: this.dataSource.length + 1
      }
      this.dataSource.push({ add: true, selectable: true, editable: true, ...defaultParam })
    },
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = this.getQueryParams() //查询条件
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.ipagination.total = res.result.total
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    save(record) {
      // 对数据进行校验
      if (!this.validate(record)) {
        return
      }

      let param = Object.assign({}, record)
      param['sourceId'] = this.mainId
      this.loading = false
      if (param.add) {
        postAction(this.url.add, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      } else {
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
            this.selectValue = ''
          })
      }
    },
    edit(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      if (target) {
        target.editable = true
        this.selectValue = target.materialCode
        this.dataSource = newData
      }
    },
    cancel(record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.id === record.id)
      if (target) {
        target.editable = false
        target.selectable = false
        this.dataSource = newData
        this.loadData()
      }
      this.selectValue = ''
    },
    onMaterialChange([, record], tableRow) {
      Object.assign(tableRow, {
        materialId: record.materialId,
        materialCode: record.materialCode,
        materialName: record.materialName,
        sap: record.sap,
        unit: record.unit,
        unit_dictText: record.unit_dictText,
        materialType: record.materialType,
        materialType_dictText: record.materialType_dictText,
        warehouse: record.warehouse,
        warehouse_dictText: record.warehouse_dictText,
        bomId: record.id,
        stepId: record.step,
        stepId_dictText: record.step_dictText
      })
    },
    validate(record) {
      // 1. 判断工序顺序是否重复
      const isStepOrderRepeat = this.dataSource.filter(item => item.stepOrder === record.stepOrder).length > 1
      const isCodeRepeat = this.dataSource.filter(item => item.materialCode === record.materialCode).length > 1
      if (isStepOrderRepeat) {
        this.$message.warning('工序顺序不能重复')
        return false
      } else if (isCodeRepeat) {
        this.$message.warning('物料代码不能重复')
        return false
      } else {
        return true
      }
    },
    editAll() {
      const newData = [...this.dataSource]
      newData.forEach(item => {
        item.editable = true
      })
      this.dataSource = newData
    },
    saveAll() {
      // 对数据进行校验
      let orders = this.dataSource.map(item => item.stepOrder)
      let orderSet = new Set(orders)
      if (orders.length !== orderSet.size) {
        this.$message.warning('工序顺序不能重复')
        return
      }
      this.loading = true
      postAction(this.url.editBatch, this.dataSource, { params: { sourceId: this.mainId } })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>

<style scoped></style>
